import React, { useState, useEffect } from "react";
import axios from "axios";
export const request = async (url) => {
  const res = await axios.get(url);
  const data = res.data;
  // if (data.code !== 200) {
  //   alert("服务器开小差了");
  //   return {};
  // }
  return data.data;
};

// 菜品信息
export const useFoods = () => {
  const [foodCategoryList, setFoodCategoryList] = useState([]);
  const [foodList, setFoodList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [sum, setSum] = useState(0);
  const [number, setNumber] = useState(0);
  const url = "https://www.xiaozhu.run/api/foods";
  const getFood = async () => {
    const foodData = await request(url);
    const foodCategoryList = foodData.categoryList;
    let foodList = foodData.foodList;
    setLoading(true);
    setFoodCategoryList(foodCategoryList);
    const newFoodList = (foodList = foodList.map((item, index) => {
      foodList[index].num = 0;
      return item;
    }));
    setFoodList(newFoodList);
  };

  // 增加数量
  const addFood = (i) => {
    const newNumber = Array.from(foodList).map((item, index) => {
      if (index === i) {
        item.num += 1;
      }
      return item;
    });
    setNumber(newNumber);
  };

  // 减少数量
  const removeFood = (i) => {
    const newNumber = Array.from(foodList).map((item, index) => {
      if (index === i) {
        if (item.num === 0) {
          item.num = 0;
        } else {
          item.num -= 1;
        }
      }
      return item;
    });
    setNumber(newNumber);
  };

  // // 计算总价
  // const getSum = () => {
  //   const sum = Array.from(foodList).forEach((item) => {
  //     return item.price * item.num;
  //   });
  //   setSum(sum);
  //   return sum;
  // };
  useEffect(() => {
    getFood();
    // getSum();
  }, []);

  return [{foodCategoryList:foodCategoryList}, {foodList:foodList}, {loading:loading},{ addFood:addFood}, {removeFood:removeFood}];
};

// 点餐信息
export const useOrders = () => {
  const [users, setUsers] = useState();
  const [orderData,setOrderData] = useState({});
  // 菜品总数量
  let [orderSum,setOrderSum]=useState(0);
  let [MoneySum,setMoneySum]=useState(0);
  const url = "https://www.xiaozhu.run/api/orders";
  const getOrder = async () => {
    const orderData = await request(url);
    setOrderData(orderData);
  
  const newOrderSum=  Object.keys(orderData).map((item, index) => {
      // 用户名 总的菜品
      //console.log(item, orderData[item]);
      Object.keys(orderData[item]).forEach((order, i) => {
        // 菜品id  菜品数量
        //console.log(order,orderData[item][order]);
        orderSum+=orderData[item][order];
        return orderSum;
      });
    });
    setOrderSum(newOrderSum);
  };
 
 
  useEffect(() => {
    getOrder();
  }, []);
  return [{orderData:orderData},{orderSum:orderSum}];
};
